package com.zyf.wjy.controller;

import com.zyf.wjy.common.Result;
import com.zyf.wjy.entity.Material;
import com.zyf.wjy.service.MaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 农资管理控制器
 */
@Controller
@RequestMapping("/material")
public class MaterialController {
    
    @Autowired
    private MaterialService materialService;
    
    /**
     * 农资列表页面
     */
    @GetMapping("/list")
    public String list(Model model) {
        List<Material> materials = materialService.findAll();
        model.addAttribute("materials", materials);
        return "material/list";
    }
    
    /**
     * 新增/编辑页面
     */
    @GetMapping("/edit")
    public String edit(@RequestParam(required = false) Long id, Model model) {
        if (id != null) {
            Material material = materialService.findById(id);
            model.addAttribute("material", material);
        }
        return "material/edit";
    }
    
    /**
     * 保存农资
     */
    @PostMapping("/save")
    @ResponseBody
    public Result<Material> save(@RequestBody Material material) {
        try {
            Material saved = materialService.save(material);
            return Result.success("保存成功", saved);
        } catch (Exception e) {
            return Result.error("保存失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除农资
     */
    @PostMapping("/delete/{id}")
    @ResponseBody
    public Result<Void> delete(@PathVariable Long id) {
        try {
            boolean success = materialService.deleteById(id);
            if (success) {
                return Result.success("删除成功", null);
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            return Result.error("删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取所有农资（用于下拉选择）
     */
    @GetMapping("/all")
    @ResponseBody
    public Result<List<Material>> getAll() {
        List<Material> materials = materialService.findAll();
        return Result.success(materials);
    }
}

